/**
 * @Copyright:Copyright (c) 1992 - 2015
 * @Company: TengTong
 */
package com.tengtong.duang.commons.convert;

import java.util.Map;

import com.tengtong.duang.commons.convert.support.MapToObjectConverter;

/**
 * 提供一个简单快捷的 转换工具
 *
 * @author jai
 * @since: v1.0
 */
public class ConversionServiceUtils {

	private final static ConversionService conversionService = ConversionServiceFactory.createDefaultConversionService();
	
	private final static MapToObjectConverter mapToObject = new MapToObjectConverter(conversionService);
	
	/**
	 * 将源数据 source ，转换成 类型为 targetType 的目标数据
	 *
	 * @param source
	 * @param targetType
	 * @return
	 */
	public static <T> T convert(Object source, Class<T> targetType) {
		return conversionService.convert(source, targetType);
	}
	
	/**
	 * 一般性转换，如果无法转换则返回 null 值
	 *
	 * @param value
	 * @param targetClass
	 * @return
	 * @throws Exception
	 */
	public static Object convertTo(Object value, Class<?> targetClass) throws Exception{		
		Object v = conversionService.convert(value, targetClass);
		if(v != ConversionService.NOT_FOUND_CONVERTER){
			return v;
		}
		return null;
	}
	
	/**
	 * 将 map 内数据转为对象数据
	 *
	 * @param datas
	 * @param targetClass
	 * @return
	 * @throws Exception
	 */
	public static Object mapToObject(Map<?, ?> datas, Class<?> targetClass) throws Exception{
		return mapToObject.convert(datas, targetClass);
	}
}
